<template>
  <el-table :data="filterTableData" border table-layout=auto style="width: 100%; font-size:18px"  
    :row-class-name="tableRowClassName"
    :default-sort="{ prop: 'made_date', order: 'descending' }"
    >

    <el-table-column label="ID" sortable prop="id" />
    <el-table-column label="名称" prop="name" />
    <el-table-column label="生产日期" sortable prop="made_date" />
    <el-table-column label="位置" prop="location" />
    <el-table-column label="是否过期" prop="expired" />
    <el-table-column label="功效" prop="usage" />
    <el-table-column align="right">
      <template #header>
        <el-row class="mb-4" style="flex-direction: row; flex-wrap: column; justify-content: space-between;">
          <el-input v-model="search" size="large" placeholder="Type to search" />
          <div class="tool">
            <el-button type="success" :icon="Edit" size="large" @click="handleCreate()">添加</el-button>
            <el-switch v-model="paginationOn" active-text="分页开" inactive-text="分页关" />
          </div>
        </el-row>

      </template>
      <template #default="scope">
        <el-button size="large" @click="handleEdit(scope.$index, scope.row)">Edit</el-button
        >
        <el-button
          size="large"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >Delete</el-button
        >
      </template>
    </el-table-column>
    
  </el-table>

  <el-pagination
    large
    background
    layout="total, prev, pager, next"
    v-model:page-size="pageSize"
    v-model:page-count="pageCount"
    v-model:total="totalItem"
    class="mt-4"
    v-model:current-page=currentPage
  />


  <el-dialog
    v-model="centerDialogVisible"
    title="添加"
    align-center
  >
    <el-form :model="form">
    <el-form-item label="名称">
      <el-input v-model="form.name"/>
    </el-form-item>
    <el-form-item label="功效">
      <el-input type=textarea v-model="form.usage"/>
    </el-form-item>
    <el-form-item label="位置">
      <el-select v-model="form.location" placeholder="选择位置">
        <el-option label="公司" value="公司" />
        <el-option label="丢弃" value="丢弃" />
        <el-option label="家" value="家" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产日期">
        <el-date-picker
          v-model="form.made_date"
          type="date"
          placeholder="Pick a date"
          value-format="YYYY-MM-DD"
        />
    </el-form-item>
    <el-form-item label="购买日期">
        <el-date-picker
          v-model="form.bought_date"
          type="date"
          placeholder="Pick a date"
          value-format="YYYY-MM-DD"
        />
    </el-form-item>
    <el-form-item label="有效期">
      <el-input-number :step=6 v-model="form.effect_months" />
    </el-form-item>
    <el-form-item label="价格（元）">
      <el-input-number :precision="2" v-model="form.price" />
    </el-form-item>
    <el-form-item label="数量">
      <el-input-number v-model="form.quantity" />
    </el-form-item>
    <el-form-item label="品牌">
      <el-input v-model="form.brand"/>
    </el-form-item>
    <el-form-item label="购买渠道">
      <el-select v-model="form.bought_from" >
        <el-option label="医院" value="医院" />
        <el-option label="药店" value="药店" />
        <el-option label="线上" value="线上" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button @click="submit()" type="primary">提交</el-button>
      <el-button @click="centerDialogVisible = false">Cancel</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</template>



<script lang="ts" setup>
var centerDialogVisible = ref(false)
import {
  Edit,
} from '@element-plus/icons-vue'
import ElMessage from 'element-plus'
import { computed, ref, onMounted, h } from 'vue'
import axios from 'axios'
import { paginationInjectionKey } from 'vue-devui/types/pagination';
const currentPage = ref(1)
const pageSize = ref(10)
const pageCount = ref(0)
const totalItem = ref(0)
const paginationOn = ref(true)

interface Medicine {
  id: number
  quantity: number
  location: string
  usage: string
  bought_from: string
  bought_date: string
  expired: boolean
  effect_months: number
  brand: string
  made_date: string
  name: string
  price: number
}

const search = ref('')
var med: Medicine = {} as Medicine

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: Medicine
  rowIndex: number
}) => {
  if (row.expired) {
    return 'warning-row'
  } else {
    return 'success-row'
  }
}


const submit = () => {
  console.log(form.value.name)
  let med = form.value
  if (med.name === "" || !med.name) {
    ElMessage({
      message: "输入名称不能为空", type: 'error',
    })
    return
  }
  if ( med.id == -1 ) {
    med.id = 0
    med.expired = true
  }
  axios.defaults.headers.post['Content-Type'] = 'application/json; charset=UTF-8';
  axios.post('/api/v1/medicine', med).then(res => {
    ElMessage({message: "操作成功", type: 'success',});
    fetchData()
    centerDialogVisible.value = false
  });
  
}

var form = ref(med);

const filterTableData = computed({
  get: () =>  {
    const searchValue = search.value.toLowerCase();
    var data = tableData.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(searchValue) ||
      data.usage.includes(searchValue)

  )
  if (! paginationOn.value) {
    pageCount.value = 1
    totalItem.value = data.length
    return data
  }
  totalItem.value = data.length
  pageCount.value = Math.round(data.length / pageSize.value + 0.49)
  return data.slice(pageSize.value*(currentPage.value-1), pageSize.value * currentPage.value)
} ,
  set: (val) => {
    search.value = '1'
    search.value = ''
  },
})

const handleEdit = (index: number, row: Medicine) => {
  var m: Medicine = {...row}
  form = ref(m)
  centerDialogVisible.value = true
}
const handleDelete = (index: number, row: Medicine) => {
  confirm("not yet supported!")
}

const handleCreate = () => {
  var m: Medicine = {} as Medicine;
  m.id = -1
  form = ref(m)
  centerDialogVisible.value = true
}

let tableData: Medicine[] = [
{
        "id": 1,
        "name": "感康",
        "price": 3.0,
        "made_date": "2021-03-09",
        "quantity": 15,
        "location": "丢弃",
        "usage": "感冒、发热",
        "bought_from": "",
        "bought_date": "",
        "expired": true,
        "effect_months": 24,
        "brand": ""
    },
];

onMounted(() => {
  fetchData()
})

const fetchData = () => {
  axios.get<Medicine[]>('/api/v1/medicines').then(res => {
    tableData = res.data;
    filterTableData.value = tableData;
  });
}
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-3);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.tool {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
}
</style>
